package com.ssps.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author li
 * @time 2020/07/24 17:08:54
 */

@Component
public class BackUpSql {

    @Value("${user.mysqldumppath}")
    private String mysqldumppath;
    //自动拿配置文件中的值，填充到这个字段中去
    String hostIP = "127.0.0.1";
    String userName = "root";
    String password = "123456";
    String savePath = "";
    String databaseName = "ssps";

    public BackUpSql(){
        savePath= System.getProperty("user.dir")+"/";
    }

    public void backUp() throws Exception {
        String fileName = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date())+".sql";
        //runtime.exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump -h 127.0.0.1 -uroot -pilovelaohan ybls  > d:/2.sql");
        //  /etc/bin/mysqldump
        Process process = Runtime.getRuntime().exec(mysqldumppath+"mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);

        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
        InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while((line = bufferedReader.readLine())!= null){
            printWriter.println(line);
        }
        printWriter.flush();

        printWriter.close();
        inputStreamReader.close();

        System.out.println("备份完毕"+mysqldumppath);

    }


}